<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-17px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          class="!w-240px"
          placeholder="请输入项目名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目编号" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          class="!w-240px"
          placeholder="请输入项目编号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目主管" prop="supervisorId">
        <el-input
          v-model="queryParams.supervisorId"
          class="!w-240px"
          placeholder="请输入项目主管"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      :data="list"
      v-loading="loading"
      empty-text="暂无记录"
      element-loading-text="Loading..."
      stripe
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      show-overflow-tooltip
    >
      <el-table-column align="center" label="项目化核算编码" prop="project_code" width="180" />
      <el-table-column align="center" label="项目名称" prop="project_name" min-width="200">
        <template #default="scope">
          <div class="namecont" v-html="highlightProjectName(scope.row.project_name)"></div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="建设单位"
        prop="construction_department"
        min-width="120"
      />
      <el-table-column
        align="center"
        label="省端项目主管"
        prop="construction_department"
        min-width="120"
      >
        <template #default="scope">
          <div
            class="namecont"
            v-html="highlightprojectSupervisor(scope.row.project_supervisor)"
          ></div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目阶段" prop="projectStage" min-width="120">
        <template #default="scope">
          <div class="flex justify-center">
            <el-tag effect="light">{{ scope.row.projectStage }} </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :icon="DocumentRemove"
            @click="handleAudit(scope.row)"
            class="text-#409eff"
            >详情</el-button
          >
          <el-button
            v-if="scope.row.projectStage === '已结束' && userRoleId === 1"
            link
            type="primary"
            :icon="Plus"
            @click="openAddDialog(scope.row)"
            class="text-#409eff"
            >案例库</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="mt-35px text-14px"
      v-model:current-page="queryParams.pageNo"
      :hide-on-single-page="value"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      background
      layout="total,sizes,prev, pager, next,jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <AddDialog ref="addCase" :editData="editData" @success="getAllProjectsList" />
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import { getUserProfile } from '@/api/system/user/profile'
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted } from 'vue'
import { DocumentRemove } from '@element-plus/icons-vue'
import { Plus } from '@element-plus/icons-vue'

import AddDialog from './components/addDialog.vue'

const { push } = useRouter() // 路由
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const value = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectCode: '',
  projectName: '',
  supervisorId: ''
})

const queryFormRef = ref()

const addCase = ref()
const editData = ref({})

//获取用户角色id
const userRoleId = ref()
const getUser = async () => {
  await getUserProfile().then((res) => {
    userRoleId.value = res.roles[0].id
  })
}

// 新增案例
const openAddDialog = (item) => {
  editData.value = item
  addCase.value.open()
}

// 条数变化
const handleSizeChange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getAllProjectsList()
}

// 页码变化
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getAllProjectsList()
}

// 查询任务列表
const getAllProjectsList = async () => {
  loading.value = true
  try {
    const data = await IctApi.getAllProjectsPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
    
    // 如果有数据，获取项目流程阶段
    if (list.value.length > 0) {
      const projectList: Array<string> = []
      list.value.forEach((item: { project_code: string }) => {
        projectList.push(item.project_code)
      })
      
      const projectsData = {
        project_code_list: projectList
      }
      
      try {
        const stageRes = await BpmApi.getProjectStage(projectsData)
        list.value.forEach(
          (item: {
            project_code: string | number
            processInstanceId: any
            projectStage: any
            tasksName: any
            finished?: boolean
          }) => {
            if (stageRes[item.project_code]) {
              item.processInstanceId = stageRes[item.project_code][0].id
              item.projectStage = item.finished
                ? '已结束'
                : stageRes[item.project_code][0].name
              item.tasksName = stageRes[item.project_code][0].process_definition_name
            }
          }
        )
      } catch (error) {
        console.error('获取项目阶段失败:', error)
      }
    }
    
    // 设置分页器显示状态
    value.value = total.value === 0
  } catch (error) {
    console.error('获取项目列表失败:', error)
    list.value = []
    total.value = 0
    value.value = true
  } finally {
    loading.value = false
  }
}

// 详情按钮跳转
const handleAudit = (row: any) => {
  push({
    name: 'ProjectDetails',
    query: {
      project_code: row.project_code
    }
  })
}

// 搜索按钮操作
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getAllProjectsList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.pageNo = 1
  getAllProjectsList()
}

// 初始化
onMounted(() => {
  getAllProjectsList()
  getUser()
})

const escapeRegExp = (string: string): string => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

const highlightProjectName = (name: string): string => {
  if (!queryParams.projectName) {
    return name
  }
  const regex = new RegExp(escapeRegExp(queryParams.projectName), 'gi')
  const newText = name.replace(regex, (match) => `<span class="highlight">${match}</span>`)
  return newText
}

const highlightprojectSupervisor = (name: string): string => {
  if (!queryParams.supervisorId) {
    return name
  }
  const regex = new RegExp(escapeRegExp(queryParams.supervisorId), 'gi')
  const newText = name.replace(regex, (match) => `<span class="highlight">${match}</span>`)
  return newText
}
</script>
<style scoped>
.el-pagination {
  justify-content: flex-end;
}
.namecont {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

:deep(.highlight) {
  background-color: yellow;
}
</style>